<template>
  <div class="client-info">
    <Title :title="title"/>
    <div class="client-form">
      <el-form
        ref="clientForm"
        :model="dataForm"
        class="edit-client el-form-box-left"
        label-position="left"
        label-width="100px">
        <el-form-item :label="title">
          <el-select
            v-model="dataForm.related"
            :remote-method="optionsList"
            :loading="loading"
            :multiple="multiple"
            :placeholder="placeholder"
            popper-class="global-select-down"
            class="remoteRequest1"
            filterable
            collapse-tags
            remote
            reserve-keyword
            size="small"
            @change="formatOption">
            <el-option
              v-for="item in relatedOptions"
              :key="item[target[0]]"
              :label="type === 1 ? `${item.number}/${item.name || '--'}` : item[target[1]]"
              :value="item[target[0]]" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import { getList } from '@/api/legal';
import { getInvoiceList } from '@/api/invoice';
export default {
  name: 'RelatedItem',
  components: { Title },

  props: {
    ids: { // 初始选中
      type: Array,
      default: () => []
    },
    options: { // 初始选项
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: '关联合同'
    },
    type: { // 1:合同 2发票
      type: Number,
      default: 1
    },
    multiple: {
      type: Boolean,
      default: true
    },
    target: {
      type: Array,
      default: () => ['id', 'number']
    },
    searchQuery: {
      type: String,
      default: 'keyword'
    },
    batchIndex: {
      type: Number,
      default: null
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      dataForm: {
        related: null
      },
      relatedOptions: [],
      cacheLen: 0,
      optionArr: []
    };
  },
  computed: {
    isMediumUser() {
      // 媒介用户：拥有媒介的权限但是没有，销售的权限
      /**
         * 规则：
         * 1、媒介用户仅看见订单及资源信息、成本信息
         * 2、媒介用户只可以编辑成本信息
         * 3、无法查看客信息（列表与详情页皆隐藏客户信息）
         * 4、客户信息包括：客户名称、销售、客户联系人、策划执行人、客户ID、客户类型
         */
      return hasRouteAuth('crm:orderList:medium') && !hasRouteAuth('crm:orderList:admin');
    }
  },
  watch: {
    ids(newV) {
      this.dataForm.related = newV;
      this.cacheLen = this.dataForm.related.length;
    },
    options(newV) {
      this.relatedOptions = newV;
      this.optionArr = newV;
    }
  },
  created() {
    this.optionsList('');
  },
  mounted() {
    if (!this.multiple) {
      window.remoteRequest('.remoteRequest1', this.optionsList);
    }
  },
  methods: {
    async optionsList(query) {
      // if (query !== '') {
      this.loading = true;
      try {
        const params = {
          [this.searchQuery]: query,
          page: 1,
          perPage: 20
        };
        if (this.type === 1) {
          const res = await getList(params);
          this.loading = false;
          this.relatedOptions = res.data.items;
          return false;
        }
        if (this.type === 2) {
          const res = await getInvoiceList(params);
          this.loading = false;
          this.relatedOptions = res.data.items;
          return false;
        }
      } catch (error) {
        console.log(error);
        this.relatedOptions = [];
      }
      // } else {
      //   this.relatedOptions = [];
      // }
    },
    formatOption(value) {
      const len = value.length;
      // console.log(this.cacheLen);
      // 选中 增加
      if (len > this.cacheLen) {
        // console.log('增加');
        const arr = this.relatedOptions.filter(item => item.id === value[len - 1]);
        // this.deleteAttr(arr, ...this.target);
        this.optionArr = [...this.optionArr, ...arr];
      } else {
        // 删除
        // console.log('删除');
        this.optionArr = this.optionArr.filter(item => value.includes(item.id));
      }
      this.cacheLen = value.length;
      this.postMessage();
    },
    // 剔除多余字段
    deleteAttr(arr, ...key) {
      arr.forEach(item => {
        Object.keys(item).forEach(e => {
          if (!key.includes(e)) {
            delete item[e];
          }
        });
      });
      // console.time('1');
      // JSON.parse(JSON.stringify(arr, [...key]));
      // console.timeEnd('1');
      // return JSON.parse(JSON.stringify(arr, [...key]));
    },
    postMessage() {
      try {
        const params = {
          ids: this.dataForm.related,
          options: this.optionArr
        };
        this.$emit('postMessage', params, this.batchIndex);
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
  .client-info {
    padding: 24px 0 0 24px;
    .client-form {
      margin-top: 32px;
    }
    &::v-deep {
      .el-tag--info {
        max-width: 90%;
        color: #406EFF;
        background-color: #ecf1ff;
        display: flex;
        align-items: center;
        .el-select__tags-text {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          padding-right: 3px;
        }
        .el-tag__close {
          flex-shrink: 0;
          right: 0;
          top: 1px;
        }
      }
    }
  }
</style>
